package com.dev.op.controller;



import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dev.op.VO.ResultVO;
import com.dev.op.VO.SubmissionVO;
import com.dev.op.entity.*;
import com.dev.op.enums.ResultCode;
import com.dev.op.service.JudgeService;
import com.dev.op.service.SubmissionService;
import com.dev.op.service.TestCaseService;
import com.dev.op.service.UserGroupAdminService;
import com.dev.op.util.JudgeResultParser;
import com.dev.op.util.RedisUtil;
import com.dev.op.util.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.UUID;


@RestController
@RequestMapping("/submissions")
@PreAuthorize("hasAnyRole('admin','teacher','student')")
public class SubmissionController {

    @Autowired
    TestCaseService testCaseService;

    @Autowired
    JudgeService judgeService;

    @Autowired
    JudgeResultParser judgeResultParser;

    @Autowired
    SubmissionService submissionService;

    @Autowired
    UserGroupAdminService userGroupAdminService;

    @Autowired
    RedisUtil redisUtil;


//    @PostMapping
//    public ResultVO<String> addSubmission(@RequestBody Submission submission) throws Exception {
//        //赋予随机ID
//        submission.setSubmissionId(UUID.randomUUID().toString());
//        //默认使用 runBatch,和非样本测试
//        SubmissionVO submissionVO = new SubmissionVO(false,submission,false);
//        //生产 任务请求
//        submissionService.saveTask(submissionVO);
//        return ResultVO.success(submission.getSubmissionId());
//    }

    @PostMapping()
    public ResultVO<String> addSubmission(@RequestBody Submission submission) throws Exception {
        //System.out.println("请求进入");
        //赋予随机ID
        submission.setSubmissionId(UUID.randomUUID().toString());
        //默认使用 runBatch,和非样本测试
        SubmissionVO submissionVO = new SubmissionVO(false,submission,false);
        //生产 任务请求
        submissionService.splitTaskAndPushToRedis(submissionVO);
        return ResultVO.success(submission.getSubmissionId());
    }


    @PostMapping("/sample-test")
    public ResultVO<List<Submission>> runSampleTest(@RequestBody Submission submission) throws Exception {
        List<Submission> submissions = submissionService.runSampleTestCases(submission);
        return ResultVO.success(submissions);
    }
    /**
     * 某用户关于某问题的全部提交
     * @param id 用户id
     * @param problemId 问题id
     * @return
     * @throws Exception
     */
    @GetMapping("/user/{user-id}/problem/{problem-id}")
    public ResultVO<Page<Submission>> getSubmissionByUserIdAndProblemId(@PathVariable("user-id") String id,
                                                                        @PathVariable("problem-id") String problemId,
                                                                        @RequestParam("page") String page,
                                                                        @RequestParam("size") String size,@AuthenticationPrincipal User user) throws Exception {
        //鉴别请求： admin可以查询所有人的，teacher只能查询 自己所在班级的人，student只能查询自己的
        List<String> roles = SecurityUtil.getCurrentUserRoles();
        //System.out.println(roles);
        if(roles.contains("admin")){
            //System.out.println("管理员");
            int userId = Integer.parseInt(id);
            Page<Submission> result = submissionService.getSubmissionsByUserIdAndProblemId(userId,problemId,Integer.parseInt(page),Integer.parseInt(size));
            return ResultVO.success(result);
        }
        //只能查看 自己 + 所管理的学生
        else if(roles.contains("teacher")){
            //System.out.println("老师");
            List<UserGroupMember> userGroupMembers = userGroupAdminService.getManagedUser(user.getId());
            Boolean check = false;
            for(UserGroupMember userGroupMember : userGroupMembers){
                if( id.equals(userGroupMember.getUserId()) ){
                    check = true;
                    break;
                }
            }
            if(!check){
                return ResultVO.error(ResultCode.FORBIDDEN.message());
            }
            else{
                int userId = Integer.parseInt(id);
                Page<Submission> result = submissionService.getSubmissionsByUserIdAndProblemId(userId,problemId,Integer.parseInt(page),Integer.parseInt(size));
                return ResultVO.success(result);
            }
        }
        //只能查看自己
        else if(roles.contains("student")){
            //System.out.println("只能查看自己");
            if(!user.getId().equals(id)){
                return ResultVO.error(ResultCode.FORBIDDEN.message());
            }
            int userId = Integer.parseInt(id);
            Page<Submission> result = submissionService.getSubmissionsByUserIdAndProblemId(userId,problemId,Integer.parseInt(page),Integer.parseInt(size));
            return ResultVO.success(result);
        }
        //System.out.println("野");
        return null;
    }

    @GetMapping ("/user/{user-id}")
    ResultVO<Page<Submission>> getSubmissionByUserId(@PathVariable("user-id") String id,@RequestParam("page") String page,
                                                                 @RequestParam("size") String size)throws Exception{
        int userId = Integer.parseInt(id);
        Page<Submission> result = submissionService.getSubmissionByUserId(userId,Integer.parseInt(page),Integer.parseInt(size));
        return ResultVO.success(result);
    }

    @GetMapping("/problem/{problem-id}")
    ResultVO<Page<Submission>> getSubmissionByProblemId(@PathVariable("problem-id") String id,@RequestParam("page") String page,
                                                        @RequestParam("size") String size) throws Exception{
        int problemId = Integer.parseInt(id);
        Page<Submission> result = submissionService.getSubmissionByProblemId(problemId,Integer.parseInt(page),Integer.parseInt(size));
        return ResultVO.success(result);
    }

    @GetMapping("/{submission-id}")
    ResultVO<Submission> getSubmission(@PathVariable("submission-id") String submissionId) throws Exception{
        Submission submission = submissionService.getById(submissionId);
        return ResultVO.success(submission);
    }



//    @DeleteMapping
//    ResultVO<Boolean> deleteSubmissionById(@PathVariable("submission-id") String submissionId) throws Exception {
//        submissionService.removeById(Integer.parseInt(submissionId));
//        return ResultVO.success(true);
//    }

//    @PutMapping("/user/{user-id}/problem/{problem-id}")
//    ResultVO<Boolean> updateSubmission(){
//
//    }


}
